package com.tianjs.current.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * lock接口实验起步
 * @author admin
 */
public class FirstLock {

	public static void main(String[] args) {
		Lock lock = new ReentrantLock();
		try {
			lock.lock();//阻塞式的获取锁(同sychronized)
			boolean flag=lock.tryLock();//非阻塞式的获取锁(没有获取到锁，则立刻返回)
			System.out.println("flag:"+flag);
			lock.lockInterruptibly();//获取到锁的线程可以响应中断
			//超时获取锁
			//1、在1s内获取锁，返回true
			//2、在1s内没有获取锁，返回false
			//3、在1s内如果被中断，返回false
			boolean timeoutFlag = lock.tryLock(1L, TimeUnit.SECONDS);
			System.out.println("timeoutFlag:"+timeoutFlag);
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			System.out.println("释放锁开始");
			lock.unlock();//显示的释放锁
			System.out.println("释放锁结束");
		}
	}

}
